/**
 *  *2010-3-16 下午02:01:06  add 
 */
package com.base.myproject.client.busi.storeslist;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.ColumnInfo;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.base.myproject.client.ui.celleditor.BaseSimpleCombox;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.Label;

/**
 * 库存商品选择
 * @author Administrator
 *2010-3-16
 * javazgw@gmail.com
 */
public class GcodeSelectDialog {

	
	
	final Window w = new Window();
	final Button yesbutton = new Button("确定");
	final Button button = new Button("取消");
	Button reloadbutton = new Button("刷新");
	
	boolean b;
	
	
	BaseGrid<BusiObject> grid;
	BaseStore<BusiObject> basestore;
	BaseStore<BusiObject> target_store;
	
	ColumnInfo[] sourcecol;
	ColumnInfo[] target_col;
	
	BaseComboBoxForm<BaseModelData>  scode;
	TextField<String> barcode;
    TextField<String> cgcode;
    TextField<String> modeltype;
    SimpleComboBox gcode ;
	public GcodeSelectDialog()
	{
	
		init();
	}

	private void init() {
		
		initWidget();
	}
	private void initWidget()
	{
		createGird();
		yesbutton.addListener(Events.Select, getListener());
		button.addListener(Events.Select, getListener());
		reloadbutton.addListener(Events.Select, getListener());
		w.setHeading("库存商品选择");
		w.setModal(true);
		w.setSize(776, 500);
		w.setMaximizable(true);
		
		
	    FormPanel panel = new FormPanel();  
	  
	    panel.setFrame(true);  
	    
//	    panel.setIcon(com.base.myproject.client.system.BaseResource.i.table());
//	    panel.setIcon(Resources.ICONS.form());  
	    panel.setHeaderVisible(false);
	    panel.setSize(750, -1);  
	    panel.setLabelAlign(LabelAlign.TOP);  
	    panel.setButtonAlign(HorizontalAlignment.CENTER);  
	    
	    TableLayout tl = new TableLayout(4);
	    TableData td = new TableData();
	    td.setPadding(5);
	    td.setColspan(1);
	    td.setRowspan(1);
	    panel.setLayout(tl);
	    
	    scode = (BaseComboBoxForm<BaseModelData> )getFormInput("scode");  
	    scode.setFieldLabel("仓库");  
	    
	   barcode = new TextField<String>();  
	    barcode.setFieldLabel("barcode");  
	    
	    cgcode = new TextField<String>();
//	    ComboBox cgcode = new ComboBox();
//	    cgcode.setStore(basestore);
	    cgcode.setFieldLabel("商品名称");  
	    
	    modeltype = new TextField<String>();  
	    modeltype.setFieldLabel("规格型号");  
	    
	    gcode = (SimpleComboBox)getFormInput("gcode");  
	   // TextField<String> gcode = new TextField<String>();  
	    gcode.setFieldLabel("类型");  
	    
	    panel.add(new Label(scode.getFieldLabel()),td);
	    panel.add(scode,td);
	    panel.add(new Label(barcode.getFieldLabel()),td);
	    panel.add(barcode,td);
	    panel.add(new Label(cgcode.getFieldLabel()),td);
	    panel.add(cgcode,td);
	    panel.add(new Label(modeltype.getFieldLabel()),td);
	    panel.add(modeltype,td);
	    panel.add(new Label(gcode.getFieldLabel()),td);
	    panel.add(gcode,td);
	    panel.setButtonAlign(HorizontalAlignment.CENTER);  
	    panel.addButton(reloadbutton);
	    w.add(panel);
	    w.add(grid);
		w.addButton(yesbutton);
		w.addButton(button);
	}
	public void createStore()
	{
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("cgicode");
		type.addField("gcode");
		type.addField("inqty");
		type.addField("outqty");
		type.addField("lastqty");
		type.addField("cgicode");
		type.addField("cgcode");
		type.addField("gcode");
		type.addField("qtyunit");
		type.addField("scode");
		type.addField("modeltype");
		type.addField("qtyunit");
		type.addField("buyprice");
		type.addField("saleprice");
		type.getField("buyprice").setType(Double.class);
		type.getField("saleprice").setType(Double.class);
		type.addField("upicode");
		StoreInfo info = new StoreInfo();
		info.setTablename("q");
		info.setNeedAllRow("no");
		info.setSql("select bcode as code ,bname as name from bcode where bcode is not null and bname is not null  ");
		basestore = new BaseStore<BusiObject>(type, info,false);
		
	}
	private void createGird()
	{
		createStore();
		CheckBoxSelectionModel<BusiObject> cbs = new CheckBoxSelectionModel<BusiObject>();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		
		columns.add(cbs.getColumn());
		//ColumnConfig bcode2 = new ColumnConfig("scode", "仓库", 100);

		//columns.add(bcode2);

		ColumnConfig bname = new ColumnConfig("cgicode", "barcode", 100);
		columns.add(bname);
		ColumnConfig cgcode = new ColumnConfig("cgcode", "商品名", 100);
	
		columns.add(cgcode);
		columns.add(new ColumnConfig("modeltype", "规格", 100));
		columns.add(new ColumnConfig("gcode", "商品类型", 100));
		
		ColumnConfig cinqty = new ColumnConfig("inqty", "入库数量", 100);
		cinqty.setNumberFormat(NumberFormat.getFormat("#,##0.00"));
		columns.add(cinqty);
		
		ColumnConfig outqty =  new ColumnConfig("outqty", "已经出库数量", 100);
		outqty.setNumberFormat(NumberFormat.getFormat("#,##0.00"));
		columns.add(outqty);
		
		ColumnConfig lastqty = new ColumnConfig("lastqty", "库存余额", 100);
		lastqty.setNumberFormat(NumberFormat.getFormat("#,##0.00"));
		
		columns.add(lastqty);
		columns.add(new ColumnConfig("buyprice", "采购单价", 100));
		columns.add(new ColumnConfig("saleprice", "销售指导单价", 100));
		columns.add(new ColumnConfig("qtyunit", "单位", 50));
		
		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BusiObject>(basestore, cm,false,false,null);
		
		grid.setSize(750, 250);
		cbs.setSelectionMode(SelectionMode.SIMPLE);
		grid.setSelectionModel(cbs);
		grid.setAutoExpandColumn("cgcode");
		grid.getView().setEmptyText("无数据");
		grid.getView().setForceFit(true);
	}
	public void show()
	{
		
		if (!b) {
			
			w.show();
			b = true;
		} else
			w.show();
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                      
				try {                                                        
					if (sync == 1) {                                           
						if (be.getType() == Events.Select) {                     
							if (be.getSource().equals(yesbutton)) {   
								
								doposted(grid.getSelectionModel().getSelectedItems());
                                                                     
							}       
							else if (be.getSource().equals(button)) {   
								close();
								
                                
							}   
							else if(be.getSource() == reloadbutton)
							{
//								field.reset();
								basestore.getStoreinfo().setSql(getsql());
								basestore.reload();
							}
						}
						else if (be.getType() == Events.Hide) {    
							
						}
						else if (be.getType() == Events.Change) {              
							if (be.getSource().equals("")) {         
                                                                     
							}                                                      
						} else if (be.getType() == Events.KeyUp) {               
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{                                                    
								}                                                    
							}                                                      
						}                                                        
					}                                                          
				} finally {                                                  
					sync--;                                                    
				}                                                            
			}

		                                                       
                                                                     
		};                                                               
		return defaultlistener;                                          
	}    
	
	public Field getFormInput(String  name)
	{
		
		if(name.equals("scode"))
		{
			
	
		ModelType scodetype = new ModelType();
		scodetype.setRoot("records");
		scodetype.setRecordName("record");

		scodetype.addField("code");

		scodetype.addField("name");

		StoreInfo scodeinfo = new StoreInfo();
		scodeinfo.setForcenolimit("true");
		 scodeinfo.setTablename("ccode");
		 scodeinfo.setSql("select code,name from dictionary where type ='2'");
		BaseStore<BaseModelData> scodestore = new BaseStore<BaseModelData>(
				scodetype, scodeinfo);
		BaseComboBoxForm<BaseModelData> scode = new BaseComboBoxForm<BaseModelData>("code",
				"name", scodestore);
		scode.setFieldLabel("仓库");
		scode.setName("scode");
		
		return scode;
		}
		else if(name.equals("gcode")){
			BaseSimpleCombox bsc =new BaseSimpleCombox("gname","gcode","");
			
			return bsc.getCombox();
		}
		return null;
	}
	
	private String getsql()
	{
		
		String filter ="1=1 ";//"(cgicode like '%' and cgcode like '%' and modeltype like '%' and gcode like '%' and scode like '%') ";
		String filter2 ="1=1 ";
		if(scode.getValue()!=null)
		{
			filter +=" and scode ='" +scode.getValue().get("code")+"'";
			filter2 +=" and upscode ='" +scode.getValue().get("code")+"'";
		}
		else 
		{
			filter +="and (scode is null or scode like '%25')";
			filter2+="and (upscode is null or upscode like '%25')";
		}
		
		if(barcode.getValue()!=null)
		{
			filter +="  and cgicode ='" +barcode.getValue()+"'";
			filter2+="  and cgicode ='" +barcode.getValue()+"'";
		}
		else 
		{
			filter +="  and (cgicode is null or cgicode like '%25')";
			filter2+="  and (cgicode is null or cgicode like '%25')";
		}
	    
		if(cgcode.getValue()!=null)
		{
			filter +="  and cgcode ='" +cgcode.getValue()+"'";
			filter2 +="  and cgcode ='" +cgcode.getValue()+"'";
		}
		else 
		{
			filter +="  and (cgcode is null or cgcode like '%25')";
			filter2+="  and (cgcode is null or cgcode like '%25')";
			
		}
		
		if(modeltype.getValue()!=null)
		{
			filter +=" and  modeltype ='" +modeltype.getValue()+"'";
			filter2+=" and  modeltype ='" +modeltype.getValue()+"'";
		}
		else 
		{
			filter +=" and  (modeltype is null or modeltype like '%25')";
			filter2+=" and  (modeltype is null or modeltype like '%25')";
			
		}
		
		
		if(gcode.getValue()!=null)
		{
			filter +=" and  gcode ='" +gcode.getValue()+"'";
			filter2+=" and  gcode ='" +gcode.getValue()+"'";
		}
		else 
		{
			filter +=" and  (gcode is null or gcode like '%25')";
			filter2+=" and  (gcode is null or gcode like '%25')";
			
		}
		
		
		String str="";
		str+="select * from (";
		str+=" select sum(a.qty) as inqty,sum(b.qty) as outqty, cast(sum(isnull(a.qty,0)-isnull(b.qty,0)) as decimal(8,2)) as lastqty ,a.cgicode,a.cgcode,a.gcode,a.qtyunit,a.modeltype,a.scode,a.upicode,max(buyprice) as buyprice,max(a.saleprice) as saleprice  from     ";
		str+=" (      ";
		str+=" select sum(qty) as qty,cgicode,cgcode,gcode,qtyunit,modeltype,scode,upicode,max(buyprice) as buyprice,max(saleprice) as saleprice from storeslistg as z1 where inoutflag=2 and  "+filter;
		str+=" group by cgicode,cgcode,gcode,qtyunit,modeltype     ,scode,upicode   ";
		str+=" ) as a ";
		str+=" full join       ";
		str+=" (      ";
		str+=" select sum(qty) as qty,cgicode,cgcode,gcode,qtyunit,modeltype,upscode as scode,originalicode from storeslistg as z1 where inoutflag=3 and  " +filter2;
		str+=" group by cgicode,cgcode,gcode,qtyunit,modeltype,upscode,originalicode  ";
		str+=" ) as b    ";
		str+=" on a.cgicode=b.cgicode and a.cgcode=b.cgcode and a.gcode = b.gcode and a.modeltype= b.modeltype   and  a.scode= b.scode and a.qtyunit=b.qtyunit and a.upicode = b.  originalicode          ";
		str+=" group by a.cgicode,a.cgcode,a.gcode,a.qtyunit,a.modeltype ,a.scode ,a.upicode          ";
		str+=" ) as z  where lastqty >0 ";
		return str;
	}
	
	public void setScode(BaseModelData scode)
	{
		this.scode.setValue(scode);
	}
	/**
	 * 提交后处理，之类继承
	 * @param at
	 */
	public  void doposted(List<BusiObject> at) {
		
		
	}
	protected void close() {
		grid = null;
		basestore = null;

		sourcecol = null;
		target_col = null;

		scode = null;
		barcode = null;
		cgcode = null;
		modeltype = null;
		gcode = null;
		w.hide();
		
	}       
}
